*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*	Store Z'Z matrix after partialling out covariates.
*	----------------------------------------------------------------------------
*	IN: 	vam_analysis_file
*
*	OUT:	ZZ.csv
*	----------------------------------------------------------------------------

	args sample sch_res ptype vtype bw
	tokenize `sample', parse("_")
	local years "`5'`6'`7'`8'"

*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

*	load

	use "${builddata}${city}_analysisfile`sample'`sch_res'`bw'.dta", clear

*	get ordering

	ivset, y(m) ptype(`ptype')
		local Dfull = r(D)
		local S = r(S)
		local p = r(P)
		local Y = r(Y)

	if "${city}" == "NYC" {
		drop enr_4555
		drop enr_2337
		drop enr_2583
		drop enr_3459
		drop enr_3552
		drop enr_6334
		drop enr_6365
		drop enr_6403
		drop enr_6524
		drop enr_6564
		drop enr_6388
	}
	if "${city}" == "NYCms" {
		drop enr_6593
		drop enr_3349
	}

	preserve

		//need schools to be represented in the lottery sample, or else first step regs have no variance ests.
		_rmcoll `Dfull' if `S', forcedrop
		local D = r(varlist)

		gen tag = 0
		foreach var of varlist `D'{
			local sch=substr("`var'",-4,.)
			replace tag = 1 if sch == `sch'
		}
		keep if tag

		keep sch lottery_`ptype'_sch omitted
		duplicates drop

		//lotteries first
		gsort omitted -lottery_`ptype'_sch sch
		gen newnum = _n

		//count schools
		local J=_N
		count if lottery_`ptype'_sch & !omitted
		local L=r(N)

		//store ordering in locals
		forval i=1/`J'{
			qui sum sch if newnum == `i'
			local oldnum_`i' = r(mean)
			di in red "`oldnum_`i''"
		}

	restore

*	estimate

	keep if `S'

	//partial out controls from offer dummies (Z_tilde)
	forval l = 1/`L'{
		qui reg offer_`oldnum_`l'' `p' $iv_controls
		predict Z`l', residuals
	}

	//construct Z'Z
	keep Z*
	matrix accum ZZ = Z*, noconstant

*	output

	clear
	svmat ZZ

	export delimited using "${builddata}${city}_`ptype'`bw'_ZZ.csv", novarnames replace
